﻿using System;
using System.Collections.ObjectModel;
using System.Xml.XPath;
using System.Globalization;

namespace CSP.CRM.ISVExtensions
{
  public partial class CreateProcedurePage : System.Web.UI.Page
  {
    protected int languageCode;
    protected string organizationName;
    protected string contactId;
    protected CspInfo csp;

    protected void ValidateQueryString()
    {
      if (Request["id"] == null)
        throw new InvalidOperationException("contactid missing");
      if (Request["userlcid"] == null)
        throw new InvalidOperationException("userlcid missing");
      if (Request["orgname"] == null)
        throw new InvalidOperationException("orgname missing");      
    }

    protected void Page_Load(object sender, EventArgs e)
    {
      try
      {

        contactId = Request["id"];
        languageCode = Int32.Parse(Request["userlcid"], CultureInfo.InvariantCulture);
        organizationName = Request["orgname"];

        System.Net.IPHostEntry ipEntries = System.Net.Dns.GetHostEntry(Request.Url.Host);
        string strServerIp = ipEntries.AddressList[0].ToString();

        string crmServerUrl = String.Format(CultureInfo.InvariantCulture, "{0}://{1}:{2}", Request.Url.Scheme, strServerIp, Request.Url.Port);

        csp = new CspInfo(new Uri(crmServerUrl), organizationName, languageCode);
        
       


        if (IsPostBack)
          return;

        Collection<EntityInfo> procedureMetadata = Application["procedureMetadata"] as Collection<EntityInfo>;

        if (procedureMetadata == null)
        {
          procedureMetadata = csp.GetProcedureMetadata();
          Application["procedureMetadata"] = procedureMetadata;
        }
        repProcedures.DataSource = procedureMetadata;
        repProcedures.DataBind();

        string initializeScript = String.Format(CultureInfo.InvariantCulture, "contactid = '{0}';", contactId);
        string openProcedureUrl = BuildNewProcedureUrl();
        initializeScript += String.Format(CultureInfo.InvariantCulture, @"openProcedureUrl = '{0}';", openProcedureUrl);
        ClientScript.RegisterClientScriptBlock(typeof(string), "kInitializeScript", initializeScript, true);
      }
      catch (Exception ex)
      {
        Response.Write(ex.Message);
        string errorScript = Server.UrlEncode(String.Format("alert('{0}');", ex.Message));
        ClientScript.RegisterClientScriptBlock(typeof(string), "kErrorScript", errorScript, true);
      }
    }


    private string BuildNewProcedureUrl()
    {
      IXPathNavigable contactDom = csp.FetchContactXml(new Guid(contactId));
      FetchHelper r = new FetchHelper(contactDom);

      string fullName = r.GetText("fullname");
      string address = r.GetText("address1_line1");
      string city = r.GetText("address1_city");
      string postalCode = r.GetText("address1_postalcode");
      string emailAddress = r.GetText("emailaddress1");
      string telephone = r.GetText("telephone1");

      string url = "/userdefined/edit.aspx";
      url += String.Format(CultureInfo.InvariantCulture, "?csp_contactid={0}&csp_contactidname={1}", contactId, fullName);
      if (address != null)
        url += String.Format(CultureInfo.InvariantCulture, "&csp_address={0}", address);
      if (city != null)
        url += String.Format(CultureInfo.InvariantCulture, "&csp_city={0}", city);
      if (postalCode != null)
        url += String.Format(CultureInfo.InvariantCulture, "&csp_postalcode={0}", postalCode);
      if (emailAddress != null)
        url += String.Format(CultureInfo.InvariantCulture, "&csp_emailaddress={0}", emailAddress);
      if (telephone != null)
        url += String.Format(CultureInfo.InvariantCulture, "&csp_phone={0}", telephone);
      return url;
    }

  }
}
